package com.zbkj.front.controller.merchant;

import com.github.pagehelper.PageInfo;
import com.zbkj.common.model.traceability.TraceableItems;
import com.zbkj.common.page.CommonPage;
import com.zbkj.common.request.PageParamRequest;
import com.zbkj.common.result.CommonResult;
import com.zbkj.service.service.TraceableItemsService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import com.zbkj.common.response.traceability.TraceableItemWithBatchResponse;

/**
 * 可追溯项管理控制器
 * +----------------------------------------------------------------------
 * | CRMEB [ CRMEB赋能开发者，助力企业发展 ]
 * +----------------------------------------------------------------------
 * | Copyright (c) 2016~2023 https://www.crmeb.com All rights reserved.
 * +----------------------------------------------------------------------
 * | Licensed CRMEB并不是自由软件，未经许可不能去掉CRMEB相关版权
 * +----------------------------------------------------------------------
 * | Author: xiaolic
 * +----------------------------------------------------------------------
 */
@Slf4j
@RestController
@RequestMapping("api/merchant/traceable-items")
@Api(tags = "商品溯源-可追溯项管理")
public class TraceableItemsController {

    @Autowired
    private TraceableItemsService traceableItemsService;

    /**
     * 生成批次的可追溯项
     * @param batchId 批次ID
     * @return 生成结果
     */
    @ApiOperation(value = "生成批次的可追溯项")
    @ApiImplicitParam(name = "batchId", value = "批次ID", required = true, dataType = "Long", paramType = "path")
    @PostMapping("/generate/{batchId}")
    public CommonResult<String> generateForBatch(@PathVariable Long batchId) {
        if (traceableItemsService.generateForBatch(batchId)) {
            return CommonResult.success("生成成功");
        } else {
            return CommonResult.failed("生成失败");
        }
    }

    /**
     * 分页查询批次的可追溯项列表
     * @param batchId 批次ID
     * @param request 分页参数
     * @return 可追溯项列表
     */
    @ApiOperation(value = "分页查询批次的可追溯项列表")
    @ApiImplicitParam(name = "batchId", value = "批次ID", required = true, dataType = "Long", paramType = "path")
    @GetMapping("/list/{batchId}")
    public CommonResult<CommonPage<TraceableItems>> getList(@PathVariable Long batchId, @Validated PageParamRequest request) {
        return CommonResult.success(CommonPage.restPage(traceableItemsService.getPageList(batchId, request)));
    }

    /**
     * 获取可追溯项详情
     * @param id 可追溯项ID
     * @return 可追溯项详情
     */
    @ApiOperation(value = "获取可追溯项详情")
    @ApiImplicitParam(name = "id", value = "可追溯项ID", required = true, dataType = "Long", paramType = "path")
    @GetMapping("/detail/{id}")
    public CommonResult<TraceableItems> getDetail(@PathVariable Long id) {
        TraceableItems detail = traceableItemsService.getDetail(id);
        if (detail != null) {
            return CommonResult.success(detail);
        } else {
            return CommonResult.failed("可追溯项不存在");
        }
    }

    /**
     * 根据批次ID和序列号获取可追溯项详情
     * @param batchId 批次ID
     * @param serialNumber 序列号
     * @return 可追溯项详情
     */
    @ApiOperation(value = "根据批次ID和序列号获取可追溯项详情")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "batchId", value = "批次ID", required = true, dataType = "Long", paramType = "path"),
            @ApiImplicitParam(name = "serialNumber", value = "序列号", required = true, dataType = "Long", paramType = "path")
    })
    @GetMapping("/detail/{batchId}/{serialNumber}")
    public CommonResult<TraceableItems> getDetailByBatchAndSerial(@PathVariable Long batchId, @PathVariable Long serialNumber) {
        TraceableItems detail = traceableItemsService.getByBatchAndSerial(batchId, serialNumber);
        if (detail != null) {
            return CommonResult.success(detail);
        } else {
            return CommonResult.failed("可追溯项不存在");
        }
    }

    /**
     * 下载二维码
     * @param id 可追溯项ID
     * @param response HTTP响应
     */
    @ApiOperation(value = "下载二维码")
    @ApiImplicitParam(name = "id", value = "可追溯项ID", required = true, dataType = "Long", paramType = "path")
    @GetMapping("/qrcode/download/{id}")
    public void downloadQrCode(@PathVariable Long id, HttpServletResponse response) {
        TraceableItems item = traceableItemsService.getDetail(id);
        if (item == null) {
            throw new RuntimeException("可追溯项不存在");
        }
        
        try {
            // 这里应该实际生成二维码图片数据，现在简单返回链接地址
            String qrCodeUrl = item.getQrCodeUrl();
            
            // 设置响应头
            response.setContentType("image/png");
            response.setHeader("Content-Disposition", "attachment; filename=" + 
                    URLEncoder.encode("qrcode_" + item.getTraceId() + ".png", "UTF-8"));
            
            // 生成二维码图片并输出
            // 实际项目中可以使用 QRCode 等库生成二维码图片
            // 这里简单返回一个文本文件作为示例
            try (OutputStream outputStream = response.getOutputStream()) {
                outputStream.write(("二维码地址: " + qrCodeUrl).getBytes());
                outputStream.flush();
            }
        } catch (IOException e) {
            log.error("下载二维码失败: {}", e.getMessage());
            throw new RuntimeException("下载二维码失败");
        }
    }
    
    /**
     * 根据产品ID分页查询所有批次下的可追溯项
     * @param productId 产品ID
     * @param request 分页参数
     * @return 带有批次信息的可追溯项列表
     */
    @ApiOperation(value = "根据产品ID分页查询所有批次下的可追溯项")
    @ApiImplicitParam(name = "productId", value = "产品ID", required = true, dataType = "Integer", paramType = "path")
    @GetMapping("/list/by-product/{productId}")
    public CommonResult<CommonPage<TraceableItemWithBatchResponse>> getListByProductId(
            @PathVariable Integer productId, 
            @Validated PageParamRequest request) {
        
        // 调用Service层查询可追溯项信息
        PageInfo<TraceableItemWithBatchResponse> pageInfo = traceableItemsService.getPageListByProductId(productId, request);
        
        // 使用CommonPage转换并返回结果
        return CommonResult.success(CommonPage.restPage(pageInfo));
    }
}
